﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Composite.Events;
using Douban.Core.Events;
using Douban.Api.Mail;

namespace Douban.Core.Messages
{
    public class MessageStack : IMessageStack
    {
        private IEventAggregator _eventAggregator;
        private Stack<Message> _innerMessageStack;

        public MessageStack(IEventAggregator eventAggregator)
        {
            _eventAggregator = eventAggregator;
            _eventAggregator.GetEvent<MessageArrivedEvent>().Subscribe(OnMessageArrived);

            _innerMessageStack = new Stack<Message>();
        }

        private void OnMessageArrived(Message message)
        { 
            _innerMessageStack.Push(message);
            if(MessageArrived != null)
                MessageArrived(this, new MessageEventArgs(message));
        }

        private void OnMessageRetrieved(Message message)
        {
            if (MessageRetrieved != null)
                MessageRetrieved(this, new MessageEventArgs(message));
        }

        #region IMessageStack Members

        public bool HasMessages()
        {
            return _innerMessageStack.Count > 0;
        }

        public void PopMessage()
        {
            if(HasMessages())
            {
                Message readyForReadMessage = _innerMessageStack.Pop();
                OnMessageRetrieved(readyForReadMessage);
                _eventAggregator.GetEvent<ReadMessageEvent>().Publish(readyForReadMessage);
            }
        }

        public int Count
        {
            get { return _innerMessageStack.Count; }
        }

        public event MessageArrivedEventHandler MessageArrived;

        public event MessageRetrievedEventHandler MessageRetrieved;

        #endregion
    }
}
